#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :save_jingdong_synchronization_datas.py
# Time  :2024/12/30 17:15
# Email :fortunatedong@163.com
# Author:by Adonli
import ast
import csv
import json
import os
from datetime import datetime
from wsgiref import headers
from jingdong_order_synchronization_kuaipu.settings.error_handler import retry_on_exception
from jingdong_order_synchronization_kuaipu.settings.logger import Loggings
logs = Loggings()


class SaveDeleteJingdongSynchronizationDatas(object):
	def __init__(self, message):
		self.message = message
		order_create_date = self.message['request']['add_jingdong_order']['order_create_date']
		date_obj = datetime.strptime(order_create_date, '%Y-%m-%d %H:%M:%S')
		self.current_year = date_obj.year
		self.current_month = date_obj.month
		self.directory = f'analyze_datas/jingdongorders/广州子公司-{self.current_year}'
		self.csv_file = f'analyze_datas/jingdongorders/广州子公司-{self.current_year}/广州子公司-{self.current_year}-{self.current_month}-delete.csv'

		self.headers = {
			"branch_id": "分支机构",
			"jingdong_business_model": "业务模式",
			"jingdong_order_id": "订单号",
			"jingdong_consignee_name": "收货人姓名",
			"jingdong_consignee_address": "收货地址",
			"jingdong_phone": "联系电话",
			"order_create_date": "下单时间",
			"jingdong_ware_name": "商品名称0",
			"jingdong_sku": "商品编码0",
			"jingdong_ware_brand": "品牌0",
			"jingdong_ware_category": "品目0",
			"jingdong_ware_model": "型号0",
			"jingdong_ware_num": "采购数量0",
			"jingdong_jd_price": "京东单价",
			"jingdong_jd_total_price": "京东总价",
			"jingdong_procurement_single_price": "采购单价0",
			"jingdong_procurement_total_price": "采购总价0",
			"kuaipu_trading_num": "交易数量0",
			"kuaipu_ware_code": "物料编码0",
			"kuaipu_ware_name": "物料名称0",
			"kuaipu_ware_category": "物料类别0",
			"kuaipu_ware_brand": "品牌0",
			"kuaipu_warehouse": "仓库0",
			"kuaipu_Specification_model": "规格型号0",
			"kuaipu_trading_unit": "交易单位0",
			"kuaipu_ware_num": "对应数量0",
			"kuaipu_price_ratio": "价格占比0",
			"kuaipu_tax_procurement_single_price": "含税单价0",
			"kuaipu_tax_ratio": "税率0",
			"kuaipu_procurement_single_price": "未税单价0",
			"kuaipu_tax_price": "税额0",
			"kuaipu_tax_total_price": "合计金额0",
			"kuaipu_total_price": "金额0",
			"kuaipu_giveaway": "赠品0",
			"kuaipu_Delivery_order": "出库单号0"
		}

		if not os.path.exists(self.directory):
			os.makedirs(self.directory)

	def _get_key_fields(self):
		return [
			"branch_id", "jingdong_business_model", "jingdong_order_id",
			"jingdong_consignee_name", "jingdong_consignee_address", "jingdong_phone",
			"order_create_date", "jingdong_ware_name", "jingdong_sku",
			"jingdong_ware_brand", "jingdong_ware_category", "jingdong_ware_model",
			"jingdong_ware_num", "jingdong_jd_price",
			"jingdong_jd_total_price","jingdong_procurement_single_price",
			"jingdong_procurement_total_price"
		]

	def _read_existing_data(self):
		if not os.path.exists(self.csv_file):
			return []
		with open(self.csv_file, 'r', newline='', encoding='utf-8-sig') as f:
			reader = csv.DictReader(f)
			return list(reader)

	def _write_data(self, data):
		with open(self.csv_file, 'w', newline='', encoding='utf-8-sig') as f:
			writer = csv.DictWriter(f, fieldnames=self.headers.keys())
			writer.writeheader()
			writer.writerows(data)

	def _process_items(self, items, is_synchronized=True):
		existing_data = self._read_existing_data()
		key_fields = self._get_key_fields()

		for new_item in items:
			# 标准化所有字段值为字符串
			standardized_new_item = {k: str(v) if v is not None else '' for k, v in new_item.items()}

			# 在现有数据中查找匹配项
			found = False
			for i, existing_row in enumerate(existing_data):
				match = all(
					str(existing_row.get(key, '')) == standardized_new_item.get(key, '')
					for key in key_fields
				)
				if match:
					# 更新kuaipu字段
					if is_synchronized:
						for key in standardized_new_item:
							if key.startswith('kuaipu_'):
								existing_data[i][key] = standardized_new_item[key]
					found = True
					break

			if not found:
				# 创建新行并填充默认值
				new_row = {key: '' for key in self.headers}
				# 填充京东字段
				for key in key_fields:
					new_row[key] = standardized_new_item.get(key, '')
				# 如果是同步数据则填充kuaipu字段
				if is_synchronized:
					for key in standardized_new_item:
						if key.startswith('kuaipu_'):
							new_row[key] = standardized_new_item.get(key, '')
				existing_data.append(new_row)

		self._write_data(existing_data)

	@retry_on_exception(max_retries=3, delay=2)
	def save_synchronization_orders_messages(self):
		base_order_info = self.message['request']['add_jingdong_order']
		result = []

		for jd_item, kp_item in zip(
				self.message['request']['add_jingdong_order_bodys']['add_jingdong_order_body'],
				self.message['request']['add_kuaipu_order_bodys']['add_kuaipu_order_body']
		):
			merged_item = {
				**base_order_info,
				**jd_item,
				**kp_item,
				# 确保所有字段都有值
				**{k: '' for k in self.headers if k not in base_order_info and k not in jd_item and k not in kp_item}
			}
			result.append(merged_item)

		self._process_items(result, is_synchronized=True)

	@retry_on_exception(max_retries=3, delay=2)
	def save_no_synchronization_orders_messages(self):
		base_order_info = self.message['request']['add_jingdong_order']
		result = []

		for jd_item in self.message['request']['add_jingdong_order_bodys']['add_jingdong_order_body']:
			merged_item = {
				**base_order_info,
				**jd_item,
				# 初始化kuaipu字段为空
				**{k: '' for k in self.headers if k.startswith('kuaipu_')}
			}
			# 确保包含所有字段
			merged_item = {**{k: '' for k in self.headers}, **merged_item}
			result.append(merged_item)

		self._process_items(result, is_synchronized=False)

	@retry_on_exception(max_retries=3, delay=2)
	def save_delete_synchronization_orders_messages(self):
		base_order_info = self.message['request']['add_jingdong_order']
		result = []

		for jd_item in self.message['request']['add_jingdong_order_bodys']['add_jingdong_order_body']:
			merged_item = {
				**base_order_info,
				**jd_item,
				# 初始化kuaipu字段为空
				**{k: '' for k in self.headers if k.startswith('kuaipu_')}
			}
			# 确保包含所有字段
			merged_item = {**{k: '' for k in self.headers}, **merged_item}
			result.append(merged_item)

		self._process_items(result, is_synchronized=False)

